package tm.data;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import tm.dto.Users;

public abstract class HibernateGenericDao implements GenericDao {

	private Class persistentClass;
	
	public HibernateGenericDao(Class realclass){
		//System.out.println("HibernateGenricDao initialized with :"+realclass.getName());
		this.persistentClass = realclass;
		//System.out.println("HibernateGenricDao initialized with :"+persistentClass.getName());
	}
	
	//@Override
	public void delete(Object obj) {
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = factory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.delete(obj);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null) tx.rollback();
			throw e;
		} finally {
			session.close();
		}

	}

	//@Override
	public List findAll() {
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = factory.openSession();
		try {
			Criteria criteria = session.createCriteria(persistentClass);
			List objects = criteria.list();
			return objects;
		} finally {
			session.close();
		}
	}

	//@Override
	public Object findById(int id) {
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = factory.openSession();
		//System.out.println("Id passed: "+id);
		Object object = null;
		try {
			object = (Object) session.load(persistentClass, id);
			return object;
		} finally {
			session.close();
		}
	}

	//@Override
	public void saveOrUpdate(Object obj) {
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = factory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.saveOrUpdate(obj);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null) tx.rollback();
			throw e;
		} finally {
			session.close();
		}

	}

}
